<?php
namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\BbsCategory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\Approve;
use App\Models\EmployExt;
use App\Models\UserCollect;
use App\User;
use App\Models\Role;
use Illuminate\Support\Facades\Log;

class MasterController extends Controller
{


    protected $user;

    public function __construct()
    {
        $this->user = Auth::user();
    }
    
    public function toApprove(Request $req)
    {
        $app = $req->input('app','');
        $app_id = $req->input('appid','0');
        $client_ip = $req->getClientIp();
        if(empty($app) || empty($app_id))
        {
            return $this->formatJson('error','缺少相关信息，不可点赞！');
        }
        $clip = ip2long($client_ip);
        $appr = Approve::where(array('app'=>$app,'app_id'=>$app_id,'client_ip'=>$clip))->get();
        if(!empty($appr) && count($appr)>0)
        {
            return $this->formatJson('error','您已经点过赞了,请勿重复点赞！'); 
        }
        $approve = new Approve();
        $approve->app = $app;
        $approve->app_id = $app_id;
        $approve->client_ip = intval($clip);
        $approve->save();
        if($app == 'employ')
        {
            $ext = EmployExt::find($app_id);
            $ext->approving_num += 1;
            $ext->save();
        }
        return $this->formatJson('success','点赞成功！');
    }

    /**
     * 格式化分类参数
     * @param unknown $fourchild
     * @param unknown $subchild
     * @param unknown $child
     * @param unknown $type
     * @return Ambigous <number, unknown>
     */
    protected function getTypes($type,$child,$subchild,$fourchild)
    {
        if(isset($fourchild) && $fourchild !== 'undefined' && $fourchild != 'null' )
        {
            $cateid = $fourchild;
        }
        else
        {
            if((isset($subchild) && $subchild != 0 && $subchild !== 'undefined' && $subchild != 'null'))
            {
                $cateid = $subchild;
            }
            else
            {
                if(isset($child) && $child != 0 && $child !== 'undefined' && $child != 'null')
                {
                    $cateid = $child;
                }
                else
                {
                    if(isset($type) && $type !== 'undefined' && $type != 'null')
                    {
                        $cateid = $type;
                    }
                    else
                    {
                        $cateid = 0;
                    }
                }
            }
        }
        return $cateid;
    }

    /**
     * 根据子分类获取父分类
     * @param  $catid
     * @param  $pid
     * @return multitype:multitype: Ambigous <multitype:, unknown>
     */
    protected function getCate($catid,$pid,$app="employ")
    {
        if($pid>0)
        {
            $this->nowCategory[$this->item] = Category::where(array('pid'=>$pid,'app'=>$app))->get();  //当前平级分类
            $upcate = Category::where(array('cat_id'=>$pid,'app'=>$app))->first();   //获取父级分类
            if(!empty($upcate))
            {
                --$this->item;
                $this->upc[] =$upcate->cat_id;
                if ($upcate->pid > 0)
                {
                    $this->getCate($upcate->cat_id,$upcate->pid);
                }
            }
            $this->nowCategory = array_sort($this->nowCategory,function ($value){
                return $value;
            });
        }
        $this->upc[] = $catid;
        return array('list'=>$this->nowCategory,'id'=>$this->upc);
    }

    /**
     * 根据分类编号获取子分类
     * @param $cid
     */
    protected function getSubCateByCid( $cid, $app = 'organization' ) {
        $SubCat = Category::where(['pid' => $cid, 'app' => $app])->first();
        $hasSubCat = empty($SubCat) ? false : true;
        return $hasSubCat;
    }

    /**
     * xiadx
     * 获得指定分类同级的所有分类，以及该分类下的子分类
     * @param int $cat_id        分类编号
     * @param bool $is_samelv     是否显示同级分类，默认false
     * @param int   $ret_depath   返回的数组类型，1是一维数组，其它则为多维数组
     * @return array
     */
    protected function getCategoryTree($cat_id = 0, $is_samelv = false, $ret_depath = 1, $app ='organization')
    {
        static $depath = 0; //层级

        if ($is_samelv === true) {
            // 获得指定分类同级的所有分类
            if ($cat_id > 0) {
                $mod_cat = Category::where(['cat_id' => $cat_id, 'app' => $app])->first();
                $parent_id = $mod_cat->parent_id;
            } else {
                //顶级分类，获取所有分类->cached()
                $parent_id = 0;
            }
        } else {
            $parent_id = $cat_id; //获取指定分类下的子分类
        }

        $total = Category::where(['pid' => $parent_id, 'app' => $app])->count();

        $cat_array =  array();
        if ($total > 0 || $parent_id == 0) {
            $data = Category::where(['pid' => $parent_id, 'app' => $app])
                        ->get();
            //加一层
            ++$depath;
            foreach ($data AS $k => $row) {
                $cat_array[$k] = array(
                    'id' => $row->cat_id,
                    'name' => $row->cat_name,
                    'pid' => $row->pid,
                    'ordernum' => $row->display_order,
                    'depath' => $depath,
                    'child_num' => 0
                );
                $cid = $row->cat_id;
                $key = count($data) - 1;
                if ($ret_depath > 1) {

                    //递归，获取子分类
                    $child = $this->getCategoryTree($cid, $is_samelv, $ret_depath, $app);

                    if (count($child > 0)) {
                        $cat_array[$k]['child'] = $child;
                        $cat_array[$k]['child_num'] = count($child);
                    }
                } else {
                    //递归，获取子分类
                    $child = $this->getCategoryTree($cid, $is_samelv, $ret_depath, $app);

                    if (count($child)) {
                        foreach ($child as $sub) {
                            $cat_array[] = $sub;
                        }
                    }
                }
            }
            //减一层
            --$depath;
        }
        return $cat_array;
    }

    /**
     * 获取分类下拉菜单
     * @param int $selectid
     * @param bool $use_ext   是否使用mobile_catalog表，扩展分类信息
     * @return string
     */
    protected function getCategoryOptions($selectid = 0)
    {
        $cate_tree = $this->getCategoryTree(0, false, 1);
        $options = '<option value="0">----无----</option>';
        foreach ($cate_tree as $cat) {
//            if ($cat['disabled'] == 1) continue; //该分类被禁用
            if ($selectid > 0 && $selectid == $cat['id']) {
                $selected = 'selected="true"';
            } else {
                $selected = '';
            }
            if ($cat['depath'] == 1) {
                $options .= sprintf('<option value="%d" %s>├ %s</option>', $cat['id'], $selected, $cat['name']);
            } else {
                $options .= sprintf('<option value="%d" %s>%s├ %s</option>', $cat['id'], $selected,
                    str_repeat('&nbsp;', $cat['depath'] * 2), $cat['name']);
            }
        }
        return $options;
    }

    public function formatJson($status='200',$msg='没有更多数据',$data=array(),$redirectUrl = '',$page=1)
    {
        $result = array(
            'status'        => $status,
            'msg'           => $msg,
            'data'          => $data,
            'redirectUrl'   => $redirectUrl,
            'pages'         => $page
        );
        return Response::json($result);
    }

    //获取子分类
	public function getSubCategory($catid)
    {
        if($catid && $catid > 0)
        {
            $categorys = DB::table('category')->where('pid',$catid)->lists('cat_id');
            if(!empty($categorys))
            {
                $category = DB::table('category')->whereIn('pid',$categorys)->lists('cat_id');
                if(!empty($category))
                {
                    $result = array_unique(array_merge($categorys,$category));
                    return $result;
                }
                return $categorys;
            }
            return array($catid);
        }
        else
        {
            return 0;
        }
    }


    /**
     * 面包屑导航
     * @param $mod 所属模块  employ teaches company bbs
     * @param integer $cateid 第一层分类id
     * @param integer $secondid 第二层分类id
     * @param integer $lastid 最后一层分类id
     * @param integer $nowCate 当前分类id
     * @param integer $modname 模块名称  就业指南、充电加油、企业招聘、青苜社区
     * @param string $name  type 为show的时候必填  文章标题
     * @param string $type  list  列表页   show 详情页
     * @param string $teachesTypeName 充电加油 需要
     * @return string
     */
    public function mianbaoxie($mod,$cateid,$secondid,$lastid,$nowCate,$modname,$name='',$type = 'list',$teachesTypeName = '',$course = '' , $courseid = 0,$course_name = '')
    {
        $checkLi = '<li class="li-nav">';
        $noCheckLi = "<li><a href='";
        $noCheckLiEnd = "</a></li><li class=\"cut-rule\">|</li>";
        $checkLiEnd = '<i class="icon-remove"></i></a></li>';
        $mianbaoxie = "<li class=\"fist-nav\"><a href=".url('/').">首&nbsp;页</a></li><li class=\"cut-rule\">|</li>";
        if(empty($nowCate))
        {
            $mianbaoxie .= $checkLi.$modname."<a href='".url('/'.$mod)."'>".$checkLiEnd;
        }
        else
        {
            if($type == 'show')
            {
                $nowCate = 0;
            }
            $mianbaoxie .= $noCheckLi. url('/'.$mod) ."'>".$modname.$noCheckLiEnd;
            if($cateid && $cateid > 0)
            {
                if($mod == 'teaches')
                {
                    if($nowCate == $cateid)
                    {
                        $mianbaoxie .= $checkLi.$teachesTypeName."<a href='".url('/'.$mod)."'>".$checkLiEnd;
                    }
                    else
                    {
                        $mianbaoxie .= $noCheckLi.$this->toFormatUrl($mod, $cateid, 0, 0)."'>".$teachesTypeName.$noCheckLiEnd;
                    }
                }
                else
                {

                    $category = Category::where(array('cat_id'=>$cateid,'app'=>$mod))->first();
                    if(!empty($category))
                    {
                        if($nowCate == $cateid)
                        {
                            $mianbaoxie .= $checkLi.$category->cat_name."<a href='".$this->toFormatUrl($mod, 0, 0, 0)."'>".$checkLiEnd;
                        }
                        else
                        {
                            $mianbaoxie .= $noCheckLi.$this->toFormatUrl($mod, $cateid, 0, 0)."'>".$category->cat_name.$noCheckLiEnd;
                        }
                    }
                }
            }
            if($cateid && $secondid && $secondid > 0)
            {
                $secondCate = Category::where(array('cat_id'=>$secondid,'app'=>$mod))->first();
                if(!empty($secondCate))
                {
                    if($nowCate == $secondid)
                    {
                        $mianbaoxie .=$checkLi.$secondCate->cat_name."<a href='".$this->toFormatUrl($mod, $cateid, 0, 0)."'>".$checkLiEnd;
                    }
                    else
                    {
                        $mianbaoxie .= $noCheckLi.$this->toFormatUrl($mod, $cateid, $secondid, 0)."'>".$secondCate->cat_name.$noCheckLiEnd;
                    }
                }
            }
            if($cateid && $lastid && $lastid>0)
            {
                $lastcategory = Category::where(array('cat_id'=>$lastid))->first();
                if(!empty($lastcategory))
                {
                    if($nowCate == $lastid)
                    {
                        $mianbaoxie .= $checkLi.$lastcategory->cat_name."<a href='".$this->toFormatUrl($mod, $cateid, $secondid, 0)."'>".$checkLiEnd;
                    }
                    else
                    {
                        $mianbaoxie .= $noCheckLi.$this->toFormatUrl($mod, $cateid, $secondid, $lastid)."'>".$lastcategory->cat_name.$noCheckLiEnd;
                    }
                }
            }
            if($type == 'show')
            {
                if( !empty($courseid) && !empty($course_name))
                {
                    if(!empty($course)){
                        if($course =='study'){
                            $mianbaoxie .= $noCheckLi."/teaches/".$courseid."'>".$course_name.$noCheckLiEnd;
                        }else{
                            $mianbaoxie .= $noCheckLi."/teaches/".$course."/".$courseid."'>".$course_name.$noCheckLiEnd;
                        }
                    }else{
                        $mianbaoxie .= $noCheckLi."/teaches/".$courseid."'>".$course_name.$noCheckLiEnd;
                    }
                }
                if(!empty($courseid) && !empty($course_name)&&!empty($course)&&($course =='organization'))
                {
                    $mianbaoxie .= $checkLi.str_limit($name,16)."<a href='"."/teaches/".$course."/".$courseid."'>".$checkLiEnd;

                }elseif(!empty($courseid) && !empty($course_name)&&!empty($course)&&($course =='study'))
                {
                    $mianbaoxie .= $checkLi.str_limit($name,16)."<a href='"."/teaches/".$courseid."'>".$checkLiEnd;

                }elseif(!empty($courseid) && !empty($course_name)&&!empty($course)&&($course =='company'))
                {
                    $mianbaoxie .= $checkLi.str_limit($name,16)."<a href='"."/teaches/".$course."/".$courseid."'>".$checkLiEnd;

                }else
                {
                    $mianbaoxie .= $checkLi.str_limit($name,16)."<a href='".$this->toFormatUrl($mod, $cateid, $secondid, $lastid)."'>".$checkLiEnd;
                }
            }
            if($mod == 'bbs')
            {
                $mianbaoxie = "<li class=\"fist-nav\"><a href=".url('/bbs').">首&nbsp;页</a></li><li class=\"cut-rule\">|</li>";
//                $mianbaoxie .="<li class=\"fist-nav\"><a href=".url('/bbs').">板&nbsp;块</a></li><li class=\"cut-rule\">|</li>";
                if( $nowCate && $nowCate > 0)
                {
                    $category = BbsCategory::where('id','=',$nowCate)->first();
                    if(!empty($category))
                    {
                        $mianbaoxie .= $noCheckLi.$this->toFormatUrl($mod, 0, 0, $nowCate)."'>".$category->title.$noCheckLiEnd;
                    }
                }
                    $mianbaoxie .= $checkLi.str_limit($name,16)."<a href='".$this->toFormatUrl($mod, 0, 0, $nowCate)."'>".$checkLiEnd;
            }
        }
        return $mianbaoxie;
    }

    /**
     * url 格式化
     * @param $mod 模块
     * @param $cateid 父层分类id
     * @param $secondid 第二层分类id
     * @param $lastid 最后一个分类id
     * @return string url地址
     */
    private function toFormatUrl($mod,$cateid,$secondid,$lastid)
    {
        $url = '/'.$mod.'/list';
        switch ($mod)
        {
            case 'employ':
                if($cateid > 0)
                    $url .= '?cateid='.$cateid;
                if ($secondid > 0)
                    $url .= '&secondid='.$secondid;
                if($lastid>0)
                    $url .= '&lastid='.$lastid;
                break;
            case 'teaches':
                if($cateid>0)
                    $url .= '/'.$cateid;
                if($secondid>0)
                    $url .= '?secondid='.$secondid;
                if($lastid>0)
                    $url .= '&lastid='.$lastid;
                break;
            case 'bbs':
                if($lastid>0)
                    $url = '/'.$mod.'/board/'.$lastid;
                break;
        }
        return url($url);
    }

    /**
     * 获取所有城市 数组
     */
    public function getAreas($limit=10)
    {
//         DB::connection()->setFetchMode(\PDO::FETCH_ASSOC);
//         $areas = DB::table('area')->where('pid','=',0)->whereIn('title',$title)->lists('area_id');
        return DB::table('area')->where('is_hot',1)->where('pid','>',0)->skip(0)->take($limit)->get();
    }

    /**
     * 根据日期统计个数
     * @param  string $table [description]
     * @param  string $date  [description]
     * @return [array]        [description]
     */
    public function getTotalByDate($tables = [], $date = 'today', $company_id = 0)
    {
        $where = '';
        switch ($date) {
            case 'today':  //今天
                $where .= ' WHERE DATE(created_at)=CURDATE()';
                break;
            case 'yesterday':  //昨天
                $where .= ' WHERE DATE(created_at)=DATE_SUB(CURDATE(),INTERVAL 1 DAY)';
                break;
            case 'this_week':  //这周
                $where .= ' WHERE YEARWEEK(created_at) = YEARWEEK(NOW())';
                break;
            case 'last_week':  // 上周
                $where .= ' WHERE YEARWEEK(created_at) = YEARWEEK(NOW())-1';
                break;

            default:
                # code...
                break;
        }
        $reult = [];
        if(is_array($tables) AND !empty($tables)) {
            foreach ($tables as $table) {
                $and_where = '';
                if($table == 'inbox')
                    $and_where .= ' AND user_id=' . $company_id;
                else
                    $and_where .= ' AND company_id=' . $company_id;

                $sql = 'SELECT COUNT(*) AS total FROM qm_' . $table . $where . $and_where;
                $reult[] = DB::select($sql)[0]->total;
            }
        }
        return $reult;
    }

    /**
     * 时间友好显示 7天内，超过3天的则会显示显示几天前，而超过7天则会显示年月日小时分钟
     * @param  $date
     * @return [type]
     */
    public function tranTime($datetime)
    {
        $time = strtotime($datetime);  //转为时间戳
        $rtime = date("m-d H:i",$time);
        $rtime2 = date("Y-m-d H:i",$time);
        $htime = date("H:i",$time);
        $time = time() - $time;
        if ($time < 60) {
            $str = '刚刚';
        }elseif ($time < 60 * 60) {
            $min = floor($time/60);
            $str = $min.'分钟前';
        }elseif ($time < 60 * 60 * 24) {
            $h = floor($time/(60*60));
            $str = $h.'小时前';
        }elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor($time/(60*60*24));
            if($d==1)
                $str = '昨天 '.$htime;
            else
                $str = '前天 '.$htime;
        }elseif ($time < 60 * 60 * 24 * 7) {
            $d = floor($time/(60*60*24));
            $str = $d.' 天前 '.$htime;
        }elseif ($time < 60 * 60 * 24 * 30) {
            $str = $rtime;
        }else {
            $str = $rtime2;
        }
        return $str;
    }

    /**
     * @敏感词过滤显示
     * @return 内容
     */
    public function filterWords($content,$wordstr)
    {
        if(!empty($wordstr)&&!empty($content)){
            $wordarr = explode(',',$wordstr);
            $newwordarr = array_combine($wordarr,array_fill(0,count($wordarr),'*'));
            $content = strtr($content, $newwordarr);
        }
        return $content;
    }

    public function isCollected($app,$app_id) 
    {
        $ucollect = array();
        if(!empty($this->user))
            $ucollect = UserCollect::where(array('app'=>$app,'app_id'=>$app_id,'user_id'=>$this->user->id))->first();
        return $ucollect;
    }

    public function changeUser()
    {
        $users = array(
            '职业导航' => array(
                '杨秘地盘','本尊狠寂寞','仲孙将断','森女空格',
                '嵇槽跳','生如夏花','萌萌的雪梨16','江爹虑江',
                '慧慧的窝_886','阿佳喜宝','米粒的天空1986',
                'Pahcy-李','大美人陪着你笑','不甜诺','本命鹿晗唯十二',
            ),
            '认证指南' => array(
                '瓶装的wl很好喝','赵官官','段段小马真伟大','图土兔two',
                '雪儿要幸福-2','让班家族','JSETJAY','奋斗青年小崔说事',
                '腊月梅花','痞人丁丁','狮子芒果','北飘南归',
                'mandy-萌萌', '少女心哈儿','霜月落花',
            ),
            '职业法则' => array(
                '龙龙不萌','黑色的就只是咖啡','lovely小伙儿还年轻',
                '费大大么么','Machine-jongin','鲁美里的闫女王大人',
                '罗大美有拖延症','我只是一只小学生','小禾CHEN','玉治板儿同学',
                '一支烟的时间','TVsun大太阳','宋婉柔','xjk-周敏怡','Carrie沐雨',
            )
        );
        $tuids = array();
        foreach ($users as $key=>$user)
        {
            
            $ids = array();
            foreach ($user as $du){
                
                $newuser = User::where('name','=',$du)->first();
                if(empty($newuser))
                {
                    $insert_new = array(
                        'name'  => $du,
                        'password'  => bcrypt('cimers123')
                    );
                    try{
                        $newuser = User::create($insert_new);
                        $userRole = Role::where('name','=','user')->first();
                        $newuser->attachRole($userRole);
                    }catch(\PDOException $e){
                        Log::info(['修改文章所属用户'=> $e->getMessage()]);
                    }
                }
                $ids[] = $newuser->id;
                $tuids[] = $newuser->id;
            }
            $firstcatid = DB::table('category')->where(['cat_name'=>$key,'app'=>'employ'])->first();
            $catids =  $this->getSubCategory($firstcatid->cat_id);
            $total = DB::table('employ')->whereIn('cat_id',$catids)->where('user_id',1)->whereNull('deleted_at')->count();
            $num =ceil($total / 15);
            foreach ($ids as $uid)
            {
                try {
                    DB::update("update qm_employ set user_id = ".$uid .
                        " where cat_id in(".implode(",", $catids).") and user_id = 1 and ISNULL(deleted_at) order by rand() limit ".$num);
                }catch (\PDOException $e){
                    Log::info(['修改文章所属用户'=> $e->getMessage()]);
                }
            }
        }
        
        $user1 = '知名OL女王';
        $u1 = $this->createUser($user1);
        DB::update("update qm_employ set user_id = ".$u1->id .
            " where title in('从容搞掂“小二报”','“搏上位”还需“耍手段”','新人职场，让你分分钟搞定你的上司','假如你的领导是岛国人') and ISNULL(deleted_at)");
        $user2 = '职场漂流人';
        $u2 = $this->createUser($user2);
        DB::update("update qm_employ set user_id = ".$u2->id .
            " where title in('第二回：屋漏遭夜雨，两场皆失意','第一回：投资需谨慎，股市有风险') and ISNULL(deleted_at)");
        $user3 = '毕业小管家';
        $u3 = $this->createUser($user3);
        DB::update("update qm_employ set user_id = ".$u3->id .
            " where title like '%实习意识的初步形成%' and ISNULL(deleted_at)");
        
        $totalt = DB::table('teaches')->where('user_id',1)->whereNull('deleted_at')->count();
        $tnum = ceil($totalt/45);
        
        foreach ($tuids as $uid)
        {
            try {
                DB::update("update qm_teaches set user_id = ".$uid.
                    " where  user_id = 1 and ISNULL(deleted_at) order by rand() limit ".$tnum);
            }catch (\PDOException $e){
                Log::info(['修改教程所属用户'=> $e->getMessage()]);
                DB::rollBack();
            }
        }
        DB::beginTransaction();
        try {
            $chsql = "update qm_teaches_chapter tc set tc.user_id = (select t.user_id from qm_teaches t where t.id =tc.teaches_id)
                    where tc.teaches_id in (select tt.id from qm_teaches tt where ISNULL(tt.deleted_at))";
            DB::update($chsql);
            $consql = "update qm_teaches_content tc set tc.user_id =(select t.user_id from qm_teaches_chapter t where t.id=tc.chapter_id)
                      where tc.chapter_id in (select tt.id from qm_teaches_chapter tt where ISNULL(tt.deleted_at))";
            DB::update($consql);
            DB::update('update qm_teaches_content_office o set o.user_id = (select t.user_id from qm_teaches_content t where t.id=o.content_id)
                    where o.content_id in(select tc.id from qm_teaches_content tc where ISNULL(tc.deleted_at))');
            DB::update('update qm_teaches_content_ppt o set o.user_id = (select t.user_id from qm_teaches_content t where t.id=o.content_id)
                    where o.content_id in(select tc.id from qm_teaches_content tc where ISNULL(tc.deleted_at))');
            DB::update('update qm_teaches_content_video o set o.user_id = (select t.user_id from qm_teaches_content t where t.id=o.content_id)
                    where o.content_id in(select tc.id from qm_teaches_content tc where ISNULL(tc.deleted_at))');
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['修改教程附属表用户'=> $e->getMessage()]);
            DB::rollBack();
        }
    }
    
    private function createUser($name){
        $newuser = User::where('name','=',$name)->first();
        if(empty($newuser))
        {
            $insert_new = array(
                'name'  => $name,
                'password'  => bcrypt('cimers123')
            );
            try{
                $newuser = User::create($insert_new);
                $userRole = Role::where('name','=','user')->first();
                $newuser->attachRole($userRole);
            }catch(\PDOException $e){
                Log::info(['修改文章所属用户'=> $e->getMessage()]);
            }
        }
        return $newuser;
    }
}

